package cumt.wxl.winterolympics.servlet;

import cumt.wxl.winterolympics.bean.Admin;
import cumt.wxl.winterolympics.dao.DAO;
import cumt.wxl.winterolympics.utils.JDBCUtil;
import cumt.wxl.winterolympics.utils.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

@WebServlet(name = "adminLoginServlet", value = "/adminLogin-servlet")
public class AdminLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String adminName = request.getParameter("adminName");
        String password = request.getParameter("password");

//        System.out.println(password);

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        if(adminName != null && password != null) {
            //解决中文字符乱码
            byte[] bytes = adminName.getBytes("ISO-8859-1");
            adminName = new String(bytes,"utf-8");
            JDBCUtil db = new JDBCUtil();
            // 创建一个用户保存下将密码和用户名保存
            Admin admin = new Admin(adminName,password);
            DAO dao = new DAO();
            try {
                //数据库连接
                Connection conn = db.getConn();
                if(dao.login(conn, admin) != null) {
                    request.getSession().setAttribute("admin", admin);
                    response.sendRedirect("jsp/admin.jsp");
                } else {
                    out.println("<h1>管理员账号或密码错误，验证失败</h1>");
                    out.println("<h2>3秒以后跳转回登录页面</h2>");
                    response.setHeader("Refresh", "3;url=jsp/adminLogin.jsp");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                out.close();
            }
        }
    }
}
